﻿using System;
using System.IO;
using System.Diagnostics;

namespace iPhoneUI.Commands
{
    public class StartProcessCmdLet : ICmdLet
    {
        public StartProcessCmdLet()
        {
        }

        public string FullPath { get; set; }

        public string Arguments { get; set; }

        public bool IsValid
        {
            get
            {
                // can't start a file or link that doesn't exist
                return File.Exists(FullPath);
            }
        }

        public void Execute()
        {
            if (string.IsNullOrEmpty(Arguments))
                Start(FullPath);
            else
                Start(FullPath, Arguments);
        }

        private static void Start(string path)
        {
            if (Path.GetExtension(path).Equals(".exe", StringComparison.InvariantCultureIgnoreCase))
                StartProcess(path);
            else 
                StartLink(path);
        }

        private static void StartLink(string FileName)
        {
            try
            {
                Process myProcess = new Process();
                myProcess.StartInfo.FileName = FileName;
                myProcess.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private static void StartProcess(string FileName)
        {
            try
            {
                if (!File.Exists(FileName))
                    return;

                Process myProcess = new Process();

                myProcess.StartInfo.UseShellExecute = true;
                myProcess.StartInfo.FileName = FileName;

                myProcess.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private static void Start(string FileName, string args)
        {
            try
            {
                if (!File.Exists(FileName))
                    return;

                Process myProcess = new Process();

                myProcess.StartInfo.FileName = FileName;
                myProcess.StartInfo.Arguments = args;

                myProcess.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
    }
}
